package com.zoagroup.funzy.util;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class JPAUtil {
	
	private static JPAUtil instance;
	private EntityManagerFactory emf;
	
	private JPAUtil() {
		this.emf = Persistence.createEntityManagerFactory("funzyJPA");
	}
	
	public static JPAUtil getInstance() {
		if (instance == null) {
			instance = new JPAUtil();
		}
		
		return instance;
	}

	
	public EntityManager getEntityManager() {
		EntityManager toReturn = emf.createEntityManager();
		toReturn.getTransaction().begin();
		return toReturn;
	}
	
	public void closeEntityFactory() {
		instance = null;
		emf = null;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getList( Class<T> classToCast, String jpql, Object... params) {
		EntityManager em = getEntityManager();
		List<T> toReturn = null;
		Query qr = em.createQuery(jpql);
		for (int i = 0; i < params.length; i++) {
			qr.setParameter(i+1, params[i]);
		}
		toReturn = qr.getResultList();
		em.getTransaction().commit();
		em.close();
		return toReturn;
	}
}
